<template>
  <view @tap.stop="()=>{ handleAudio() }" class="audio" :key="index">
    <image :src="hasPlay ? active : stop" />
    <view>{{ surplusTime | formatTime }}</view>
  </view>
</template>


<script lang="ts">
import { IMAGE_CDN } from "@/config/index.ts";
const src =
  "http://xthk.oss-cn-shenzhen.aliyuncs.com/teach/2020-11-30/1606705701896_0.8366339649927976_%E6%98%A5%E9%A3%8E%E4%B8%80%E9%A1%BE.wav";
const active = `${ IMAGE_CDN }/active.png`
const stop = `${ IMAGE_CDN }/stop.png`
import { Component, Vue, Prop, Watch } from "vue-property-decorator";
import Taro from "@tarojs/taro";
@Component({
  filters: {
    formatTime: (value) => {
      if (value)
        return `${Math.max(Math.floor(value / 60), 0)}'${Math.max(
          Math.round(value % 60),
          0
        )}''`;
      return "播放";
    },
  },
})
export default class Audio extends Vue {
  /* 音频文件 */
  audioContext = null;
  active: string = active;
  stop: string = stop;
  timer = null;
  surplusTime: number = 0;
  durations: number = 0;
  /* 音频解析错误 */
  audioError: boolean = false;

  /* 音频地址 */
  @Prop(String) readonly src: string;
  /* index */
  @Prop([Number, String]) index;
  /* 单点播放index */
  @Prop({ default: -1 }) readonly playFlag;

  /* 本实例是否在播放 */
  get hasPlay() {
    return this.mediaVideoFlag === this.index;
  }
  get mediaVideoFlag(){
    return this.$store.getters.mediaVideoFlag
  }
  
  @Watch("mediaVideoFlag")
  onPlayFlagChanged(val, oldVal) {
    if (val !== -1 && this.index === val) {
      if (this.audioError || !this.src) {
        this.$store.commit('setMediaVideoFlag',-1)
        return Taro.showToast({ title: "音频文件错误", icon: "none" });
      }
      console.log(val);
      this.audioContext.play();
    } else {
      this.stopTimer();
      this.audioContext.stop();
    }
  }

  beforeDestroy() {
    /* 销毁音频实例 */
    this.audioContext.destroy();
  }

  mounted() {
    /* TODO: 音频被打断 缓冲 事件处理 */
    this.surplusTime = this.durations;
    this.audioContext = Taro.createInnerAudioContext();
    Taro.setInnerAudioOption({
      obeyMuteSwitch: false,
    });
    this.audioContext.src = this.src;
    this.audioContext.onEnded((res) => {
      this.$emit("handleAudio", -1);
 
      clearInterval(this.timer);
      this.timer = null;

      this.surplusTime = this.durations;
    });
    this.audioContext.onCanplay((res) => {
      this.audioContext.duration;
      // 必须。不然也获取不到时长
      setTimeout(() => {
        /* console.log(this.audioContext.duration, "this.audioContext.duration;"); */
        this.durations = this.audioContext.duration;
        this.surplusTime = Math.round(this.durations);
      }, 100);
    });
    /* 播放进度更新 */
    this.audioContext.onTimeUpdate((res) => {
      /* 已获取时长取消监听 -- 官方推荐最好不监听 */
      if (!this.durations) {
        this.durations = this.audioContext.duration;
        this.surplusTime = Math.round(this.durations);
        this.timer = setInterval(() => {
          /* if (this.surplusTime <= 0) {
          clearInterval(this.timer);
          this.timer = null;
        } */
          this.surplusTime--;
        }, 1000);
      } else {
        console.log("取消监听");
        this.audioContext.offTimeUpdate();
      }
    });
    this.audioContext.onPlay(() => {
      console.log("开始播放");
      if (this.surplusTime) {
        this.timer = setInterval(() => {
          this.surplusTime--;
        }, 1000);
      }
    });
    this.audioContext.onError((res) => {
      this.audioError = true;
      console.log(res.errMsg);
      console.log(res.errCode);
    });
    this.audioContext.onPause(() => {
      console.log("暂停");
    });
    this.audioContext.onStop(() => {
      this.surplusTime = this.durations;
    });
  }

  /* 停止计时 */
  stopTimer() {
    clearInterval(this.timer);
    this.timer = null;
  }
  /* 操作音频 -- 播放和暂停操作 */
  handleAudio() {
    /* this.$emit("update:playFlag", this.hasPlay ? -1 : this.index); */
    this.$emit("handleAudio", this.hasPlay ? -1 : this.index);
    /* this.mediaPlayFlag = this.hasPlay ? -1 : this.index */
    /* this.$emit("update:mediaPlayFlag", this.hasPlay ? -1 : this.index); */
    /* if (!this.src)
      return Taro.showToast({ title: "没有音频文件", icon: "none" });
    console.log(this.isPlay);
    this.isPlay ? this.audioContext.pause() : this.audioContext.play();
    this.isPlay = !this.isPlay; */
  }
}
</script>

<style lang="scss">
@import "@/assets/scss/tools.scss";
.audio {
  width: 100%;
  min-height: 80px;
  max-width: 100%;
  border-radius: 16px;
  background: rgba(255, 215, 0, 0.2);
  border: 2px solid #ffeea9;
  color: #a13d0f;
  font-weight: bold;
  padding: 0 32px;
  @include normal-flex(space-between);
  > image {
    width: 36px;
    height: 36px;
  }
}
</style>